# -*- coding: UTF-8 -*-
import base64
import hashlib
import hmac
import json
import time
import uuid

import requests

from lj_orm import tool_channel
from lj_tool import tool_json, tool_log

from . import tool_cache
from . import lj_bean_conn


class ToolHaikang:
    def __init__(self, conn: lj_bean_conn.BeanConn):
        self.url = conn.url
        self.appKey = conn.app_key
        self.appSecret = conn.app_secret
        tool_log.info(f"初始化海康远程api {conn.app_key}")

    def sign(self, path):
        x_ca_nonce = str(uuid.uuid4())
        x_ca_timestamp = str(int(round(time.time()) * 1000))
        sign_str = f"POST\n*/*\napplication/json\nx-ca-key:{self.appKey}\nx-ca-nonce:{x_ca_nonce}\nx-ca-timestamp:{x_ca_timestamp}\n{path}"
        temp = hmac.new(self.appSecret.encode(),
                        sign_str.encode(), digestmod=hashlib.sha256)
        return base64.b64encode(temp.digest()).decode(), x_ca_nonce, x_ca_timestamp

    def build_headers(self, signature, x_ca_nonce, x_ca_timestamp):
        return {
            "Accept": "*/*",
            "Content-Type": "application/json",
            "x-ca-key": self.appKey,  # appKey，即 AK
            "x-ca-signature-headers": "x-ca-key,x-ca-nonce,x-ca-timestamp",
            "x-ca-signature": signature,  # 需要计算得到的签名，此处通过后台得到
            "x-ca-timestamp": x_ca_timestamp,  # 时间戳
            "x-ca-nonce": x_ca_nonce  # UUID，结合时间戳防重复
        }

    def do_post(self, path, params=None):
        # 计算签名
        signature, x_ca_nonce, x_ca_timestamp = self.sign(path)
        # 封装headers
        headers = self.build_headers(signature, x_ca_nonce, x_ca_timestamp)
        # 发送请求
        res = requests.post(f"{self.url}{path}", data=json.dumps(
            params), headers=headers,  verify=False)

        # 检查响应状态码
        if res.status_code == 200:
            # 获取响应数据
            data = res.json()
            # 返回数据
            return data.get("data")
        else:
            print('请求失败')

    def init_params(self):
        return {
            "pageNo": 1,
            "pageSize": 20
        }

    def pageBmunicipal(self):
        return self.doPost("/artemis/api/bmunicipal/v1/artemis/cover/query/page", self.init_params())

    def getStreamUrlByCameraIndexCode(self, cameraIndexCode, streamUrlProtocol):
        params = self.init_params()
        params["cameraIndexCode"] = cameraIndexCode
        params["protocol"] = streamUrlProtocol
        params["expand"] = "streamform=rtp"
        res = self.do_post("/artemis/api/video/v1/cameras/previewURLs", params)
        if res:
            return res.get("url")

    def getOldStreamUrlByCameraIndexCode(self, cameraIndexCode, streamUrlProtocol, beginTime, endTime):
        params = self.init_params()
        params["cameraIndexCode"] = cameraIndexCode
        params["protocol"] = streamUrlProtocol
        params["beginTime"] = beginTime.isoformat()
        params["endTime"] = endTime.isoformat()
        params["recordLocation"] = 1
        params["expand"] = "streamform=rtp"
        return self.doPost("/artemis/api/video/v1/cameras/playbackURLs", params)

    def ListRegionByParentIndexCode(self, parentIndexCode):
        params = self.init_params()
        params["parentIndexCode"] = parentIndexCode
        return self.doPost("/artemis/api/resource/v1/regions/subRegions", params)

    def listCameraByRegionIndexCode(self, regionIndexCode):
        params = self.init_params()
        params["regionIndexCode"] = regionIndexCode
        return self.doPost("/artemis/api/resource/v1/camera/advance/cameraList", params)


@tool_cache.lj_wrapper_cache("tool_haikang_init_default")
def initDefault():
    bean_conn_instance = lj_bean_conn.BeanConn(
        "http://117.158.156.150:801", "23991440", "G9MvIH2NnYQ4hLJ1eG6p")
    return ToolHaikang(bean_conn_instance)


def initPlatDefault():
    channel = tool_channel.get_channel("40289f5a7e3c994d017e3c998daf0000")
    bean_conn_instance = lj_bean_conn.BeanConn(
        f"http://{channel.endpoint}", channel.app_key, channel.app_secret)
    return ToolHaikang(bean_conn_instance)
